package com.xc.demo.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xc.demo.common.Result;
import com.xc.demo.entity.Goods;
import com.xc.demo.entity.Orders;
import com.xc.demo.entity.OrdersGoods;
import com.xc.demo.service.GoodsService;
import com.xc.demo.service.OrdersGoodsService;
import com.xc.demo.service.OrdersService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/orders")
public class OrdersController {


    @Resource
    private OrdersService ordersService;

    @Resource
    private GoodsService goodsService;

    @Resource
    private OrdersGoodsService ordersGoodsService;






    @PostMapping
    public Boolean saveOrders(@RequestBody Orders orders){
        return ordersService.saveOrUpdate(orders);
    }

//    批量删除接口
    @PostMapping("/delOrders/batch")
    public Boolean deleteBatch(@RequestBody List<Integer> ids){
        return ordersService.removeByIds(ids);
    }


//    更新发货状态
    @PutMapping
    public Orders update(@RequestBody Orders orders){

        ordersService.updateById(orders);

        return orders;

    }



    //实现分页效果
    @GetMapping("/page")
    public IPage<Orders> findPage(@RequestParam Integer pageNum,
                                  @RequestParam Integer pageSize,
                                  @RequestParam(defaultValue = "") String uname


    ){

        IPage<Orders> page= new Page<>(pageNum,pageSize);

        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("pay_state",1);



        if(!"".equals(uname)){
            queryWrapper.like("name",uname);
        }

        queryWrapper.orderByAsc("id");

        return ordersService.page(page,queryWrapper);
    }


    @DeleteMapping("/{id}")
    public Boolean deleteOrders(@PathVariable Integer id){
        return    ordersService.removeById(id);
    }



    @RequestMapping("/getGoodsById/{id}")
    public Result getGoodsById(@PathVariable("id") Long id){
        QueryWrapper<OrdersGoods> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id",id);
        ArrayList<Goods> goods = new ArrayList<>();
        List<OrdersGoods> ordersGoodsList =  ordersGoodsService.list(queryWrapper);
        for (OrdersGoods ordersGoods : ordersGoodsList) {
            Long productId = ordersGoods.getProductId();
            Goods goods1 = goodsService.getById(productId);
            goods1.setQuantity(ordersGoods.getQuantity());
            goods.add(goods1);
        }
        return Result.success(goods);
    }

}
